package com.sl.utils.str;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

// 将一个字符串按照zip方式压缩和解压缩
public class ZipUtil {

    // 压缩
    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        return out.toString("ISO-8859-9");
    }

    // 解压缩
    public static String uncompress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str
                .getBytes("ISO-8859-9"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
// toString()使用平台默认编码，也可以显式的指定如toString("GBK")
        return out.toString();
    }

    // 测试方法
    public static void main(String[] args) throws IOException {
        System.out.println(hardwareInfo.utils.ZipUtil.compress("U2FsdGVkX1+mBJprWkQ7PV2V51fGZ8XrlMjVTcDTnGtq+RB0VxkVr2JMoQLogDznJCInYg3iyHRiyNXwlwYD0R04v6w7Lh5DfgS0lg6DtaBZ93Z6M4I5OCW7ocIBVoavnaQotlHR6hDvF8zttQ2aMlxwnKoE0al+UJRAI34UFss="));
//        System.out.println(ZipUtil.uncompress(ZipUtil.compress("{\"cpuSerial\":\"BFEBFBFF000906E9\",\"macAddress\":[\"18-60-24-98-CD-F6\"],\"mainBoardSerial\":\"PGWVC0ACYAJ1QC\"}")));
    }

}